package com.cloud.sample.util;

import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * XML辅助类
 *
 * @author fengwenjin
 * @since 2021/12/20
 */
@Slf4j
public class XMLHelper {
    /**
     * 读取xml转换为对象
     *
     * @param input
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T readValue(InputStream input, Class<T> clazz) {
        try {
            JacksonXmlModule module = new JacksonXmlModule();
            XmlMapper mapper = new XmlMapper(module);
            return mapper.readValue(input, clazz);
        } catch (Exception e) {
            log.error("readValue error", e);
        }
        return null;
    }

    /**
     * 对象转换为xml
     *
     * @param obj
     * @return
     */
    public static String writeAsString(Object obj) {
        try {
            JacksonXmlModule module = new JacksonXmlModule();
            XmlMapper mapper = new XmlMapper(module);
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("writeValueAsString error", e);
        }
        return null;
    }
}
